package com.ikas.ai.framework.jexl;

import com.google.common.collect.Maps;
import com.ikas.ai.framework.jexl.function.MathFunction;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: jexl工厂
 * @Author: qi.yilai
 * @Date: 2023/6/14 10:57
 * @Version: 1.0.0
 **/
public class JexlEngineFactory {

    public static JexlEngine jexlEngine = null;

    public static JexlEngine getInstance() {
        if (Objects.nonNull(jexlEngine)) {
            return jexlEngine;
        }
        synchronized (JexlEngineFactory.class) {
            if (Objects.nonNull(jexlEngine)) {
                return jexlEngine;
            }
            JexlBuilder jexlB = new JexlBuilder().charset(StandardCharsets.UTF_8).cache(1024).strict(true).silent(false);
            initFunction(jexlB);
            jexlEngine = jexlB.create();
            return jexlEngine;
        }
    }

    public static void initFunction(JexlBuilder jexlB) {
        Map<String, Object> functions = Maps.newHashMap();
        MathFunction mathFunction = new MathFunction();
        functions.put(mathFunction.namespace(), mathFunction);
        jexlB.namespaces(functions);
    }
}
